package com.iot.hmi.protocol;

import com.iot.hmi.entity.IotDeviceItem;
import com.iot.hmi.utils.SqliteHelper;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class ProtocolHandler extends Thread {
    private final Integer period;
    private final AbstractProtocol protocol;
    private final List<IotDeviceItem> deviceItems;
    private volatile boolean isShaderStart = false;

    public ProtocolHandler(
            AbstractProtocol protocol,
            List<IotDeviceItem> deviceItems,
            Integer period
    ) {
        this.period = period;
        this.protocol = protocol;
        this.deviceItems = deviceItems;
    }

    public void startShader() {
        this.isShaderStart = true;
    }

    public void closeShader() {
        this.isShaderStart = false;
    }

    @Override
    public void run() {
        for (; ; ) {
            if (Thread.currentThread().isInterrupted()) {
                return;
            }
            if (!protocol.isConnected()) {
                return;
            }
            if (deviceItems.isEmpty()) {
                return;
            }
            if (!isShaderStart) {
                return;
            }
            try {
                TimeUnit.SECONDS.sleep(period);
            } catch (InterruptedException e) {
                return;
            }
            for (IotDeviceItem deviceItem : deviceItems) {
                try {
                    final String value = protocol.read(deviceItem);
                    if (value == null) {
                        continue;
                    }
                    SqliteHelper.insertIotItemValue(
                            protocol.deviceInfo().getProtocolHost(),
                            protocol.deviceInfo().getProtocolPort(),
                            deviceItem.getItemAddress(), Double.parseDouble(value) * 0.0001
                    );
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }
}
